package xyz.lwm.lazycat.ds;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import xyz.lwm.lazycat.setting.Setting;

import javax.sql.DataSource;

/**
 * default datasource provider
 *
 * @author lwm
 */
public class HikariDatasourceProvider implements DatasourceProvider {

    @Override
    public DataSource getDatasource(DatasourceProperties properties) {

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(properties.getDriverClassName());
        config.setJdbcUrl(properties.getUrl());
        config.setUsername(properties.getUsername());
        config.setPassword(properties.getPassword());
        config.setPoolName(properties.getPoolName());
        config.setConnectionTestQuery(properties.getValidationQuery()); // 客户端创建连接等待超时时间,如果30秒内没有获取连接则抛异常,不再继续等待
        config.setMinimumIdle(properties.getMinimumIdle()); // 连接池中最小空闲连接数
        config.setMaximumPoolSize(properties.getMaximumPoolSize()); // 连接池中最大连接数
        config.setIdleTimeout(properties.getIdleTimeout()); // 连接允许最长空闲时间,如果连接空闲时间超过1分钟,则会被关闭
        config.setMaxLifetime(properties.getMaxLifetime()); // 连接最长生命周期,当连接存活时间达到30分钟之后会被关闭作退休处理
        config.setValidationTimeout(properties.getValidationTimeout()); // 测试连接是否空闲的间隔
        config.setLeakDetectionThreshold(properties.getLeakDetectionThreshold()); // 连接被占用的超时时间,超过1分钟客户端没有释放连接则强制回收该连接,防止连接泄漏

        return new HikariDataSource(config);
    }

}
